<?php

/**
 * @package Framework03
 * @author Walter Tamboer
 */

/**
 * The Localization Model will handle support for different kind of languages.
 */
class LocalizationModel extends Model
{
	/**
	 * @var string The name or identifier of the current language. This name should match the base name of the language file.
	 */
	private $Language;
	/**
	 * @var string The path to the languages directory.
	 */
	private $LanguagePath;
	/**
	 * @var array This array contains all id's which can be used.
	 */
	private $LanguageList;
	/**
	 * Initializes a new instance of this class.
	 */
	public function __construct()
	{
		parent::__construct();

		$this->Language = Settings::Singleton()->Get('language');
		
		$this->LoadLanguages();
	}
	/**
	 * Loads all languages from the language directory.
	 */
	public function LoadLanguages()
	{
		// Load all languages if settings are set.
		$this->LanguagePath = Settings::Singleton()->Get('languagePath', false);

		if (!$this->LanguagePath)
			return ;

		$this->LanguageList = array();

		if (is_dir($this->LanguagePath))
		{
			$DirHandle = dir($this->LanguagePath);

			while (($Item = $DirHandle->read()) !== false)
			{
				$ItemPath = $DirHandle->path . '/' . $Item;

				if (!is_dir($ItemPath))
				{
					$BaseName = basename($ItemPath, '.php');

					$this->LanguageList[$BaseName] = array();
				}
			}
		}
		else if (Settings::Singleton()->Get('debug'))
			throw new Exception('Failed to load languages because the language directory "' . $this->LanguagePath . '" doesn\'t exist.', 404);
	}
	/**
	 * Sets the current language.
	 * @param string $Name The name or identifier of the current language.
	 */
	public function SetLanguage($Name)
	{
		$this->Language = $Name;
	}
	/**
	 * Sets an $ID with it's corresponding value for a given language.
	 * @param string $Language The language name to set the $ID of.
	 * @param string $ID The id that needs to be added or adjusted.
	 * @param string $Value The value of the ID to set.
	 */
	public function Set($Language, $ID, $Value)
	{
		$this->LanguageList[$Language][$ID] = $Value;
	}
	/**
	 * Gets the translation of the given $ID.
	 * @param string $ID The identifier that needs to be translated.
	 * @return string Returns a string with the translation of $ID.
	 */
	public function Translate($ID)
	{
		$ArgCount = func_num_args() - 1; // Minus the $ID.

		if (!array_key_exists($this->Language, $this->LanguageList))
			return $ID;

		$Language = $this->LanguageList[$this->Language];

		if (!array_key_exists($ID, $Language))
			return $ID;

		$Format = $Language[$ID];

		if ($ArgCount > 0)
		{
			$ArgumentList = func_get_args();

			array_shift($ArgumentList);
			
			return vsprintf($Format, $ArgumentList);
		}
		else
			return $Format;
	}
}

?>